<?php

namespace App\Http\Controllers;

use App\Models\Photo;
use App\Models\Message;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Storage;

class MemorialController extends Controller
{
    // 首页
    public function index(Request $request)
    {
        // 检查是否是 AJAX 请求（加载更多）
        if ($request->ajax()) {
            $type = $request->get('type', 'photos'); // photos 或 messages
            $page = $request->get('page', 1);

            if ($type === 'photos') {
                $photos = Photo::latest()->paginate(6, ['*'], 'page', $page);
                return response()->json([
                    'success' => true,
                    'data' => $photos->items(),
                    'hasMore' => $photos->hasMorePages(),
                    'nextPage' => $photos->hasMorePages() ? $photos->currentPage() + 1 : null
                ]);
            } else {
                $messages = Message::latest()->paginate(5, ['*'], 'page', $page);
                return response()->json([
                    'success' => true,
                    'data' => $messages->items(),
                    'hasMore' => $messages->hasMorePages(),
                    'nextPage' => $messages->hasMorePages() ? $messages->currentPage() + 1 : null
                ]);
            }
        }

        // 初始页面加载，只加载第一页数据
        $photos = Photo::latest()->paginate(6, ['*'], 'photos_page');
        $messages = Message::latest()->paginate(5, ['*'], 'messages_page');
        $candleCount = Message::count(); // 每条留言代表一次"点亮"

        return view('memorial.index', compact('photos', 'messages', 'candleCount'));
    }


// 上传照片（支持多图上传，每张图片可有独立描述）
    public function uploadPhoto(Request $request)
    {
//        \Log::info('Upload request received', [
//            'is_ajax' => $request->ajax(),
//            'wants_json' => $request->wantsJson(),
//            'headers' => $request->headers->all(),
//            'all_data' => $request->all(),
//            'files' => $request->allFiles()
//        ]);

        try {
            // 修改验证规则以支持多文件上传
            $request->validate([
                'photos.*' => 'required|image|mimes:jpeg,png,jpg|max:10240', // 明确指定允许的图片格式                'photos' => 'required|array|max:10', // 限制最多10个文件
                'captions' => 'nullable|array', // 描述可以为空
                'captions.*' => 'nullable|string|max:255|regex:/^[a-zA-Z0-9\x{4e00}-\x{9fa5}\s\p{P}]+$/u',
            ], [
                'photos.required' => '请选择至少一张照片',
                'photos.*.required' => '请选择有效的图片文件',
                'photos.*.image' => '文件必须是图片格式',
                'photos.*.max' => '每张照片大小不能超过10MB',
                'photos.max' => '一次最多上传10张照片',
                'captions.*.max' => '每张照片的描述不能超过255个字符',
            ]);
        } catch (\Illuminate\Validation\ValidationException $e) {
            \Log::error('Validation failed', ['errors' => $e->errors()]);

            if ($request->ajax() || $request->wantsJson()) {
                return response()->json([
                    'success' => false,
                    'message' => '验证失败：' . implode(', ', collect($e->errors())->flatten()->toArray())
                ], 422);
            }

            throw $e;
        }

        try {
            $uploadedPhotos = [];
            $duplicatePhotos = [];
            $errors = [];

            // 获取所有文件和对应的描述
            $files = $request->file('photos');
            $captions = $request->input('captions', []);

            // 处理每个上传的文件
            foreach ($files as $index => $file) {
                // 检查文件是否有效
                if (!$file->isValid()) {
                    $errors[] = "第" . ($index + 1) . "个文件上传失败，请检查文件格式和大小";
                    continue;
                }

                // 获取对应的描述（如果存在）
                $caption = isset($captions[$index]) ? $captions[$index] : '';

                // 获取上传文件的信息
                $originalName = $file->getClientOriginalName();
                $fileSize = $file->getSize();

                // 生成文件的哈希值用于检测重复
                $fileHash = hash_file('md5', $file->getPathname());

                // 检查是否已存在相同文件
                $existingPhoto = Photo::where('file_hash', $fileHash)->first();

                if ($existingPhoto) {
                    \Log::info('Duplicate photo detected', ['existing_photo_id' => $existingPhoto->id]);
                    $duplicatePhotos[] = $originalName;
                    continue;
                }

                // 保存文件
                $path = $file->store('photos', 'public');

                // 创建照片记录
                $photo = Photo::create([
                    'path' => $path,
                    'caption' => $caption,
                    'original_name' => $originalName,
                    'file_size' => $fileSize,
                    'file_hash' => $fileHash
                ]);

                $uploadedPhotos[] = $photo;
            }

            // 准备响应信息
            $messageParts = [];
            if (count($uploadedPhotos) > 0) {
                $messageParts[] = "成功上传" . count($uploadedPhotos) . "张照片";
            }

            if (count($duplicatePhotos) > 0) {
                $messageParts[] = "跳过" . count($duplicatePhotos) . "张重复照片";
            }

            if (count($errors) > 0) {
                $messageParts[] = "上传失败" . count($errors) . "张照片";
            }

            $message = implode("，", $messageParts);

            // 对于 AJAX 请求，总是返回 JSON 响应
            if ($request->ajax() || $request->wantsJson()) {
                \Log::info('Returning JSON response', ['uploaded_count' => count($uploadedPhotos)]);
                return response()->json([
                    'success' => count($uploadedPhotos) > 0 || count($duplicatePhotos) > 0, // 只要没有错误就算成功
                    'message' => $message,
                    'uploaded_count' => count($uploadedPhotos),
                    'duplicate_count' => count($duplicatePhotos),
                    'error_count' => count($errors)
                ]);
            }

            \Log::info('Returning redirect response');
            // 对于普通表单提交，执行重定向
            if (count($uploadedPhotos) > 0 || count($duplicatePhotos) > 0) {
                return redirect()->back()->with('success', $message);
            } else {
                return redirect()->back()->withErrors(['error' => $message]);
            }
        } catch (\Exception $e) {
            \Log::error('Upload error', [
                'message' => $e->getMessage(),
                'trace' => $e->getTraceAsString()
            ]);

            if ($request->ajax() || $request->wantsJson()) {
                return response()->json([
                    'success' => false,
                    'message' => '上传失败：' . $e->getMessage()
                ], 500);
            }

            return redirect()->back()->withErrors(['error' => '上传失败']);
        }
    }



    // 提交留言
    public function storeMessage(Request $request)
    {
        try {
            $request->validate([
                'content' => 'required|string|max:500|regex:/^[a-zA-Z0-9\x{4e00}-\x{9fa5}\s\p{P}]+$/u',
                'name' => 'nullable|string|max:50|regex:/^[a-zA-Z0-9\x{4e00}-\x{9fa5}_\-\s]+$/u',
            ]);

            $message = Message::create([
                'name' => e($request->input('name') ?: '一位朋友'), // 使用e()函数转义
                'content' => e($request->input('content')), // 使用e()函数转义
            ]);

            // 检查是否是 API 请求或者需要返回 JSON 响应
            if ($request->wantsJson() || $request->is('api/*') || $request->expectsJson() || $request->ajax()) {
                return response()->json([
                    'success' => true,
                    'message' => '感谢你为D仔点亮一盏灯🕯️',
                    'data' => $message,
                    'candleCount' => Message::count() // 返回最新的计数
                ]);
            }

            return redirect()->back()->with('success', '感谢你为D仔点亮一盏灯🕯️');
        } catch (\Exception $e) {
            if ($request->wantsJson() || $request->is('api/*') || $request->expectsJson() || $request->ajax()) {
                return response()->json([
                    'success' => false,
                    'message' => '提交失败：' . $e->getMessage()
                ], 400);
            }

            return redirect()->back()->withErrors(['error' => '提交失败']);
        }
    }

    // 点亮一盏灯
    public function lightCandle(Request $request)
    {
        try {
            Message::create([
                'name' => '一位朋友',
                'content' => '为D仔点亮一盏灯🕯️',
            ]);

            $candleCount = Message::count();

            if ($request->wantsJson() || $request->is('api/*') || $request->expectsJson() || $request->ajax()) {
                return response()->json([
                    'success' => true,
                    'candleCount' => $candleCount
                ]);
            }

            return redirect()->back()->with('success', '感谢你为D仔点亮一盏灯🕯️');
        } catch (\Exception $e) {
            if ($request->wantsJson() || $request->is('api/*') || $request->expectsJson() || $request->ajax()) {
                return response()->json([
                    'success' => false,
                    'message' => '操作失败：' . $e->getMessage()
                ], 400);
            }

            return redirect()->back()->withErrors(['error' => '操作失败']);
        }
    }

}
